package com.bos.service.impl;

import com.bos.dao.repositories.MenuRepository;
import com.bos.dao.repositories.PermsRepository;
import com.bos.dao.repositories.RoleRepository;
import com.bos.domian.system.Role;
import com.bos.service.RolesService;
import org.apache.struts2.components.If;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.List;

/**
 * @author misterWei
 * @create 2018年12月31号:16点00分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Transactional(rollbackFor = {NullPointerException.class, ParseException.class,NumberFormatException.class})
public class RolesServiceImpl implements RolesService {
    @Autowired
    private  RoleRepository roleRepository;

    @Autowired
    private PermsRepository permsRepository;

    @Autowired
    private MenuRepository menuRepository;

    /**
     * 根据用户Id查询当前用户的角色
     *
     * @param userId 用户Id
     * @return 返回当前用户所有的角色
     */

    @Override
    public List<Role> findByUser(Integer userId) {
        if (userId == 1) {
            return roleRepository.findAll();
        }
        return roleRepository.getByUserRole(userId);
    }

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Override
    public void save(String menuArray, Role model, String[] permissionIds) {
       if (permissionIds != null && permissionIds.length >=1){
           for (String permissionId : permissionIds) {
               model.getPermissions().add(permsRepository.getOne(Integer.parseInt(permissionId)));
           }
       }

        if (menuArray != null) {
            String[] menuIds = menuArray.split(",");
            for (String menuId : menuIds) {
              model.getMenus().add(menuRepository.getOne(Integer.parseInt(menuId)));
            }
        }
        roleRepository.saveAndFlush(model);
    }

}
